package com.xiangmo.travel.Controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiangmo.travel.Annotation.TokenRequired;
import com.xiangmo.travel.Dto.*;
import com.xiangmo.travel.Dvo.TableCollectDvo;
import com.xiangmo.travel.Dvo.TeamInfoDvo;
import com.xiangmo.travel.Dvo.TeamUserDvo;
import com.xiangmo.travel.Entity.Team;
import com.xiangmo.travel.Entity.TeamRequest;
import com.xiangmo.travel.Entity.User;
import com.xiangmo.travel.Enums.CodeAndMsg;
import com.xiangmo.travel.Service.NoticeService;
import com.xiangmo.travel.Service.TeamService;
import com.xiangmo.travel.Service.UserService;
import com.xiangmo.travel.Utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/team")
public class TeamController {
    @Autowired
    private TeamService teamService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeService noticeService;

    //team部分--------------------
    //创建、发起组队  如果已经存在 不可再进行组队
    @TokenRequired
    @PostMapping("/teams/creat")
    public ResultData<Team> addTeam(@RequestBody TeamDto teamDto, @RequestHeader("Authorization") String token){
        if(teamService.checkTeamByUserIdAndAttractionsId(teamDto.getUserId(), teamDto.getAttractionsId()) == 1){
            return new ResultData<>(CodeAndMsg.TEAM_ERROR.getCode(),
                    CodeAndMsg.TEAM_ERROR.getMessage(), null, token.substring(7));
        }
        if(teamService.addTeam(teamDto) >= 1){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                    CodeAndMsg.SUCCESS.getMessage(), null, token.substring(7));
        }
        log.warn("创建、发起组队失败！");
        return new ResultData<>(CodeAndMsg.ERROR.getCode(),
                CodeAndMsg.ERROR.getMessage(), null, token.substring(7));
    }

    //解散、取消组队
    @TokenRequired
    @DeleteMapping("/teams/delete/{teamId}")
    public ResultData<Team> deleteTeam(@PathVariable Long teamId, @RequestHeader("Authorization") String token){
        if(teamService.deleteTeam(teamId) >= 1){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                    CodeAndMsg.SUCCESS.getMessage(), null, token.substring(7));
        }
        log.warn("解散、取消组队失败！");
        return new ResultData<>(CodeAndMsg.ERROR.getCode(),
                CodeAndMsg.ERROR.getMessage(), null, token.substring(7));
    }

    //根据景点id查询组队的信息，组队完成的不展示
    @TokenRequired
    @GetMapping("/teams/query/{id}")
    public ResultData<Page<Team>> queryTeam(@RequestParam int pageNum,@RequestParam int pageSize, @PathVariable Long id, @RequestHeader("Authorization") String token){
        Page<Team> page = teamService.queryTeam(pageNum, pageSize, id);
        return new ResultData<Page<Team>>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), page, token.substring(7));
    }

    //结束组队状态
    @TokenRequired
    @PutMapping("/teams/changeStatus/{id}")
    public ResultData<User> changeStatusTeam(@PathVariable Long id, @RequestHeader("Authorization") String token){
        if(teamService.changeTeamStatus(id) >= 1){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                    CodeAndMsg.SUCCESS.getMessage(), null, token.substring(7));
        }
        log.warn("结束组队状态失败！");
        return new ResultData<>(CodeAndMsg.ERROR.getCode(),
                CodeAndMsg.ERROR.getMessage(), null, token.substring(7));
    }

    //根据用户id查询个人创建的队伍
    @TokenRequired
    @GetMapping("/teams/{userId}")
    public ResultData<PageInfoDto<TeamInfoDvo<List<User>>>> getMyTeamByUserId(@PathVariable Long userId, @RequestParam int pageNum, @RequestParam int pageSize, @RequestHeader("Authorization") String token){
        PageInfoDto<TeamInfoDvo<List<User>>> list = teamService.getMyTeamByUserId(userId, pageNum, pageSize);
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), list, token.substring(7));
    }

    //根据队伍id查询队长信息
    @TokenRequired
    @GetMapping("/teams/user/{teamId}")
    public ResultData<User> getTeamUserByTeamId(@PathVariable Long teamId, @RequestHeader("Authorization") String token){
        User user = teamService.getTeamUserByTeamId(teamId);
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), user, token.substring(7));
    }

    //根据队伍id查询队伍信息
    @TokenRequired
    @GetMapping("/teams/team/{teamId}")
    public ResultData<Team> getTeamByTeamId(@PathVariable Long teamId, @RequestHeader("Authorization") String token){
        Team team = teamService.getTeamByTeamId(teamId);
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), team, token.substring(7));
    }

    //team_user部分---------------
    //添加队伍成员
    @TokenRequired
    @PostMapping("/teamUser/creat")
    public ResultData<User> addTeamUser(@RequestBody TeamUserDto teamUserDto, @RequestHeader("Authorization") String token){
        //判断是否已经存在了
        if(teamService.checkTeamUserByUserIdAndTeamId(teamUserDto.getUserId(), teamUserDto.getTeamId()) == 1){
            return new ResultData<>(CodeAndMsg.TEAM_USER_ERROR.getCode(),
                    CodeAndMsg.TEAM_USER_ERROR.getMessage(), null, token.substring(7));
        }
        //插入新数据
        if(teamService.addTeamUser(teamUserDto) >= 1){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                    CodeAndMsg.SUCCESS.getMessage(), null, token.substring(7));
        }
        log.warn("添加队伍成员失败！");
        //插入失败
        return new ResultData<>(CodeAndMsg.ERROR.getCode(),
                CodeAndMsg.ERROR.getMessage(), null, token.substring(7));
    }


    //删除队伍成员 队长踢人和队友主动退出
    @TokenRequired
    @DeleteMapping("/teamUser/delete/{userId}/{teamId}")
    public ResultData<User> deleteTeamUser(@PathVariable Long userId, @PathVariable Long teamId, @RequestHeader("Authorization") String token){
        //通过token获取用户id
        Long tokenUserId = tokenUtil.getTokenValue(token);
        //校验用户是否有权限：为队长或为删除自己的数据 1为自己操作 2为队长操作
        TeamUserDto teamUserDto = new TeamUserDto();
        teamUserDto.setUserId(userId);
        teamUserDto.setTeamId(teamId);
        if(teamService.checkTeamUserRoot(teamUserDto, tokenUserId) <= 0){
            return new ResultData<>(CodeAndMsg.ERROR_ROOT.getCode(),
                    CodeAndMsg.ERROR_ROOT.getMessage(), null, token.substring(7));
        }
        //发送通知
        //删除操作
        if(teamService.deleteTeamUser(userId, teamId) >= 1){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                    CodeAndMsg.SUCCESS.getMessage(), null, token.substring(7));
        }
        log.warn("删除队伍成员失败！");
        //删除失败
        return new ResultData<>(CodeAndMsg.ERROR.getCode(),
                CodeAndMsg.ERROR.getMessage(), null, token.substring(7));
    }

    //查询已加入的队员,这里只能查到用户id，还需要进一步通过用户id进行用户信息查询
    @TokenRequired
    @GetMapping("/teamUser/query/{teamId}")
    public ResultData<List<TeamUserInfoDto>> queryTeamUser(@PathVariable Long teamId, @RequestHeader("Authorization") String token){
        List<TeamUserDvo> teamUserList = teamService.queryTeamUser(teamId);
        List<TeamUserInfoDto> listResult = new ArrayList<>();
        //封装数据
        for(TeamUserDvo t : teamUserList){
            User user = new User();
            TeamUserInfoDto teamUserInfoDto = new TeamUserInfoDto();
            user = userService.getUserById(t.getUserId());
            teamUserInfoDto.setName(user.getName());
            teamUserInfoDto.setAge(user.getAge());
            teamUserInfoDto.setEmail(user.getEmail());
            teamUserInfoDto.setPhone(user.getPhone());
            teamUserInfoDto.setSex(user.getSex());
            teamUserInfoDto.setUserIcon(user.getImage());
            teamUserInfoDto.setTeamCount(t.getTeamCount());
            listResult.add(teamUserInfoDto);
        }
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), listResult, token.substring(7));
    }

    //根据用户id查询个人加入的队伍
    @TokenRequired
    @GetMapping("/teamRequest/{userId}")
    public ResultData<PageInfoDto<TeamInfoDvo<List<User>>>> getOtherTeamByUserId(@PathVariable Long userId, @RequestParam int pageNum,
                                                                                 @RequestParam int pageSize, @RequestHeader("Authorization") String token){
        PageInfoDto<TeamInfoDvo<List<User>>> list = teamService.getOtherTeamByUserId(userId, pageNum, pageSize);
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), list, token.substring(7));
    }

    //team_request部分------------
    //新建请求 队员申请加入
    @TokenRequired
    @PostMapping("/teamRequest/creat")
    public ResultData<User> addTeamRequest(@RequestBody TeamRequestDto teamRequestDto, @RequestHeader("Authorization") String token){
        //判断是否已经存在了
        if(teamService.checkTeamRequestByUserIdAndTeamId(teamRequestDto.getUserId(), teamRequestDto.getTeamId()) == 1){
            return new ResultData<>(CodeAndMsg.TEAM_USER_ERROR.getCode(),
                    CodeAndMsg.TEAM_USER_ERROR.getMessage(), null, token.substring(7));
        }
        //插入新数据
        if(teamService.addTeamRequest(teamRequestDto) == 1){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                    CodeAndMsg.SUCCESS.getMessage(), null, token.substring(7));
        }
        log.warn("队员申请加入失败！");
        //插入失败
        return new ResultData<>(CodeAndMsg.ERROR.getCode(),
                CodeAndMsg.ERROR.getMessage(), null, token.substring(7));
    }

    //查询
    @TokenRequired
    @GetMapping("/teamRequest/query/{teamId}")
    public ResultData<Page<TeamRequest>> queryTeamRequest(@RequestParam int pageNum, @RequestParam int pageSize,
                                             @PathVariable Long teamId, @RequestHeader("Authorization") String token){
        Page<TeamRequest> teamRequestPage = teamService.queryTeamRequest(pageNum, pageSize, teamId);
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), teamRequestPage, token.substring(7));
    }

    //队员取消请求 删除请求
    @TokenRequired
    @DeleteMapping("/teamRequest/delete/{id}")
    public ResultData<User> deleteTeamRequest(@PathVariable Long id, @RequestHeader("Authorization") String token){
        //通过token获取用户id
        Long userId = tokenUtil.getTokenValue(token);
        //校验用户是否有权限：为队长或为删除自己的数据 1为自己操作 2为队长操作
        TeamRequestDto teamRequestDto = new TeamRequestDto();
        teamRequestDto.setUserId(userId);
        if(teamService.checkTeamRequestRoot(teamRequestDto, userId) == 0){
            return new ResultData<>(CodeAndMsg.ERROR_ROOT.getCode(),
                    CodeAndMsg.ERROR_ROOT.getMessage(), null, token.substring(7));
        }
        //删除操作
        if(teamService.deleteTeamRequest(id) == 1){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                    CodeAndMsg.SUCCESS.getMessage(), null, token.substring(7));
        }
        log.warn("删除请求队员失败！");
        //删除失败
        return new ResultData<>(CodeAndMsg.ERROR.getCode(),
                CodeAndMsg.ERROR.getMessage(), null, token.substring(7));
    }

    //获取当前景点前6天组队次数
    @GetMapping("/table/{attractionId}")
    public ResultData<List<TableCollectDvo>> getTop6CollectByAttractionId(@PathVariable Long attractionId){
        List<TableCollectDvo> list = teamService.getTop6TeamById(attractionId);
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(),
                CodeAndMsg.SUCCESS.getMessage(), list, null);
    }


}
